#include <QBuffer>

#include <dynamicmodel.h>
#include <logfileadapter.h>
#include <admfileadapter.h>

DynamicModel * readLogFile(QString & log, LogFileAdapter * adapter)
{
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    buffer.write(log.toAscii());
    buffer.seek(0);

    DynamicModel * model = adapter->createModel(&buffer);

    return model;
}

void usage()
{
    qDebug("usage: arslog2xml <log_file> <xml_file>");
}

void initMetaTypes()
{
    qRegisterMetaType<ARSObject::Types>("ARSObject::Types");
    qRegisterMetaType<ARSDummyObject *>("ARSDummyObject *");
    qRegisterMetaType<ARSDummyForm *>("ARSDummyForm *");
    qRegisterMetaType<ARSDummyActiveLink *>("ARSDummyActiveLink *");
    qRegisterMetaType<ARSDummyFilter *>("ARSDummyFilter *");
    qRegisterMetaType<ARSDummyField *>("ARSDummyField *");
    qRegisterMetaType<ARSDummyGuide *>("ARSDummyGuide *");
}

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        usage();
        return 1;
    }

    LogFileAdapter * adapter = new LogFileAdapter();
    if(!adapter->loadSettings())
    {
        qDebug("Cannot load settings.");
        return 1;
    }

    initMetaTypes();

    QFile logFile(QString::fromAscii(argv[1]));
    if(!logFile.open(QFile::ReadOnly))
    {
        qDebug("Cannot open log file.");
        return 1;
    }

    QString logString = logFile.readAll();
    logFile.close();
    DynamicModel * model = readLogFile(logString, adapter);

    QFile xmlFile(QString::fromAscii(argv[2]));
    if(!xmlFile.open(QFile::WriteOnly))
    {
        qDebug("Cannot open destanation file for writing.");
        return 1;
    }

    ADMFileAdapter * admAdapter = new ADMFileAdapter();
    admAdapter->loadSettings();
    QString xmlString = admAdapter->model2xml(model);
    xmlFile.write(xmlString.toAscii());
    xmlFile.close();

    delete adapter;

    return 0;
}
